<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="岗位名称">
          <el-input clearable placeholder="请输入岗位名称" v-model="queryParams.key"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchQuery" style="margin-left:30px;" size="small">查询</el-button>
          <el-button type="primary" @click="handleSynchro" size="small">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <section class="table-btn">
        <el-button @click="handleAdd" type="primary" icon="plus" size="small">添加岗位</el-button>
        <el-button @click="handleDown" type="primary" icon="swap" size="small">下载模板</el-button>
        <el-upload
          style="display: inline-block;margin-left: 10px"
          action=""
          :show-file-list="false"
          :http-request="handleUpload"
          :accept="getFiles()"
        >
          <el-button type="primary" icon="import" size="small">批量导入</el-button>
        </el-upload>
      </section>

      <el-table border :data="tableData" style="width: 100%" row-key="positionId">
        <el-table-column prop="positionId" label="岗位ID"></el-table-column>
        <el-table-column prop="positionSn" label="岗位编号"> </el-table-column>
        <el-table-column prop="positionName" label="岗位名称"></el-table-column>
        <el-table-column prop="positionDuty" label="岗位职责"></el-table-column>
        <el-table-column prop="isEnable" label="岗位状态">
          <template slot-scope="scope">
            <div>{{ getLabel(scope.row.isEnable) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="creater" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row.positionId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total, prev, pager, next"
        @current-change="pageHandleChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalPageNum"
      ></el-pagination>
    </el-card>

    <station-modal ref="stationModal" @ok="stationModalOk"></station-modal>
  </section>
</template>

<script>
import { accountIsEnable } from './js/constants'
import StationModal from './components/StationModal'
import { getPositionList, deletePosition, downPositionTemp, importPositionFile } from './js/auth'

export default {
  name: 'StationList',
  components: { StationModal },
  data () {
    return {
      currentPage: 1,
      pageSize: 10,
      totalPageNum: 0,
      queryParams: {},
      tableData: []
    }
  },
  created () {
    this.initData()
  },
  methods: {
    // 查询按钮
    searchQuery () {
      this.currentPage = 1
      this.initData()
    },

    // 获取部门列表
    async initData () {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      const {
        code,
        data: { list, total },
        msg
      } = await getPositionList(Object.assign({}, this.queryParams, params))
      if (code === 0) {
        this.tableData = list
        this.totalPageNum = total
      } else {
        this.$message.warning(msg)
      }
    },

    // 岗位新增
    handleAdd () {
      this.$refs.stationModal.add()
    },

    // 岗位修改
    handleEdit (row) {
      this.$refs.stationModal.edit(row)
    },

    // 删除按钮
    handleDelete (positionId) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dataDelete(positionId)
        })
        .catch(() => {
          this.$message.warning('已取消删除')
        })
    },
    // 删除函数
    async dataDelete (positionId) {
      const { code, msg } = await deletePosition([positionId])
      if (code === 0) {
        this.$message.success('删除成功')
        if (this.tableData.length === 1 && this.currentPage > 1) {
          this.currentPage--
        }
        this.initData()
      } else {
        this.$message.warning(msg)
      }
    },

    // 下载模板
    async handleDown () {
      try {
        const { code } = await downPositionTemp()
        if (code === 0) {
          this.$message.success('模板下载成功')
        }
      } catch (e) {
        this.$message.warning(e.msg)
      }
    },

    // 上传限制
    handleUpload (res) {
      let uploadFileObj = res.file
      const isSheet =
        res.file.type === 'application/vnd.ms-excel' ||
        res.file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isSheet) {
        return this.$message.error('上传文件只能是Excel格式!')
      }
      this.fileUploadFun(uploadFileObj)
    },

    // 上传文件
    async fileUploadFun (fileObj) {
      let param = new FormData()
      param.append('file', fileObj)
      const { code, msg } = await importPositionFile(param)
      if (code === 0) {
        this.$message.success('批量导入成功')
        this.initData()
      } else {
        this.$message.warning(msg)
      }
    },

    // 岗位CU弹框回调
    stationModalOk () {
      this.initData()
    },

    // 获取label
    getLabel (val) {
      return this.$base.constFormatter(accountIsEnable, val)
    },

    // 页码改变
    pageHandleChange (page) {
      this.currentPage = page
      this.initData()
    },

    // 限制上传的类型
    getFiles () {
      // excel
      let files = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']
      return files.join(',')
    },

    // 刷新按钮
    handleSynchro () {
      this.$confirm('将手动同步所有岗位信息，是否继续执行？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.initData()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-inner {
  .table-btn {
    margin-bottom: 15px;
  }
}
</style>
